package com.ryan.demo.jms.producer.active.spring;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import com.ryan.demo.jms.producer.ProducerService;

public class SpringProducerServiceImpl implements ProducerService {

	private static final Logger logger = Logger.getLogger(SpringProducerServiceImpl.class);
	private JmsTemplate jmsTemplate;
	private Destination destination;

	public void sendMessage(final Object message) {
		logger.info("before send message!");
		if (null != message) {
			MessageCreator messageCreator = new MessageCreator() {
				public Message createMessage(Session session) {
					TextMessage textMessage = null;
					try {
						textMessage = session.createTextMessage(String.valueOf(message));
					} catch (JMSException e) {
						e.printStackTrace();
					}
					return textMessage;
				}
			};
			try {
				jmsTemplate.send(this.destination, messageCreator);
			} catch (JmsException e) {
				logger.error(e.getMessage(), e);
			}
			logger.info("after send message!");
		}
	}

	public void sendMessageByCorrelationId(final Object message, final String correlationId) {
		logger.info("before send message by correlationId!");
		if (null != message) {
			MessageCreator messageCreator = new MessageCreator() {
				public Message createMessage(Session session) {
					TextMessage textMessage = null;
					try {
						textMessage = session.createTextMessage(String.valueOf(message));
						textMessage.setJMSCorrelationID(correlationId);
					} catch (JMSException e) {
						e.printStackTrace();
					}
					return textMessage;
				}
			};

			jmsTemplate.send(this.destination, messageCreator);
			logger.info("after send message by correlationId!");
		}
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}
}
